import axios from 'axios'
import utils from 'ts-element/packages/utils/utils'
import cookie from './cookie'
import NProgress from 'nprogress'
// import cookies from 'vue-cookies'
import cfg from './config/config'
// import store from '../store'
let Base64 = require('js-base64').Base64

const CancelToken = axios.CancelToken
NProgress.configure({ showSpinner: false })
const request = axios.create({
    baseURL: process.env.VUE_BASE_URL,
    timeout: Number(process.env.AJAX_TIMEOUT) * 1000,
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'x-requested-with': 'XMLHttpRequest'
    },
    onUploadProgress: p => { return 100 * (p.loaded / p.total) },
    onDownloadProgress: p => { return 100 * (p.loaded / p.total) }
})

// 数据加密
function encrypt(config, notHead) {
    let _header = config.headers['Content-Type'].indexOf('multipart/form-data')
    let url = config.url.split('/')
    let keystr = '/' + url[1]
    let str = ''
    let urlencoded = config.headers['Content-Type'].indexOf('application/x-www-form-urlencoded')
    let json = config.headers['Content-Type'].indexOf('application/json')
    let ts = ''
    if (notHead === true) {
        keystr = ''
    }
    if (url[1] !== 'user') {
        // user屏蔽
        for (let i in url) {
            if (i > 1) {
                str += '/' + url[i]
            }
        }
        if ((config.method === 'get' || config.method === 'GET') && _header == -1) {
            str = cookie.encrypt(str, 1, keystr)
            ts = '.ts'
        } else if (_header == -1) {
            str = cookie.encrypt(str, 1, keystr)
            if (json > -1) {
                config.data = cookie.encrypt(JSON.stringify(config.data), 0, keystr)
            } else {
                config.data.forEach((v, l) => {
                    let str = ''
                    let val = ''
                    if (urlencoded > -1) {
                        val = config.data.get(l)
                    } else {
                        val = v
                    }
                    if (typeof val === 'object') {
                        str = JSON.stringify(v)
                    } else {
                        str = v
                    }
                    if (urlencoded > -1) {
                        config.data.set(l, cookie.encrypt(str, 0, keystr))
                    } else {
                        config.data[l] = cookie.encrypt(str, 0, keystr)
                    }
                })
            }
            ts = '.ts'
        }
        config.url = '/' + url[1] + '/' + str + ts
    }
    return config
}

// 关闭加载层
function closeLoad() {
    global.req = global.req || []
    let len = global.req ? global.req.length : 0
    let index = 0
    for (let i in global.req) {
        index++
        if (global.req[i] === false) {
            global.req[i] = true
            break
        }
    }
    if (len === index) {
        global.req = []
        // store.commit('setLoading', false)
        // mModal.loading.close()
    }
}

request.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    const parames = utils.getparames()
    let token = localStorage.getItem('token') || localStorage.getItem('THPMSCookie')
    let data = config.data || {}
    let offEncrypt = cfg.offEncrypt
    let offHead = cfg.offHead
    let begurl = config.url
    if (typeof data === 'string') {
        data = JSON.parse(data)
        config.data = data
    }
    // if (token === null || token === 'undefined') { // 优先地址栏传入的token，配合his端
    token = parames.token || token
    if (!token && parames.t) {
        token = decodeURIComponent(Base64.decode(parames.t.split('BBSS')[1]))
    }
    // let thpCookie = token && token.indexOf('.ts') > -1 ? parames.JSESSIONID : token
    // window.$cookies.set('THPMSCookie', thpCookie)
    // 如果关闭浏览器重新跳回登录界面需要设置 token 为 Session
    // cookies.set('token', token, 'Session') // 请求头设置 token
    // let dd = decodeURIComponent(token)
    if (token) {
        localStorage.setItem('token', token);
        localStorage.setItem('THPMSCookie', token);
    } else {
        goLogin()
    }
    // }
    // 请求头设置 token
    if (token) {
        config.headers['token'] = token
    }
    if (config.method === 'get' || config.method === 'GET') {
        let pms = ''
        Object.keys(data).forEach((v, i) => {
            if (pms === '') {
                pms = v + '=' + data[v]
            } else {
                pms += '&' + v + '=' + data[v]
            }
        })
        if (config.url.indexOf('?') === -1 && pms !== '') {
            config.url = config.url + '?' + pms
        } else if (pms !== '') {
            config.url = config.url + '&' + pms
        }
    }
    if (config.headers['Content-Type'].indexOf('application/x-www-form-urlencoded') > -1) {
        let d = new URLSearchParams()
        Object.keys(data).forEach((v, i) => {
            d.append(v, data[v])
        })
        config.data = d
    }
    if (Array.isArray(global.req) === false) {
        global.req = []
    }
    if (config.loading !== false) {
        NProgress.start()
        // store.commit('setLoading', true)
        // mModal.loading.open()
        global.req.push(false)
    }
    delete config.loading
    config.cancelToken = new CancelToken(function executor(c) {
        if (typeof config.cancel === 'function') {
            config.cancel(c)
        }
    })
    delete config.cancel
    // 加密
    let hstate = -1
    if (begurl) {
        begurl = begurl.split('/')
        if (Array.isArray(offHead) === true) {
            offHead = offHead.toString()
            if (offHead.indexOf(begurl[1]) > -1) {
                hstate = 2
            }
        }
        if (Array.isArray(offEncrypt) === true && Array.isArray(offHead) === false) {
            offEncrypt = offEncrypt.toString()
            if (offEncrypt.indexOf(begurl[1]) > -1) {
                hstate = 1
            }
        }
    }
    if (cfg.isEncrypt !== false && hstate !== 1 && hstate !== 2) {
        // 加密
        config = encrypt(config)
    } else if (cfg.isEncrypt !== false && hstate === 2) {
        // 去头加密
        config = encrypt(config, true)
    }
    return config
}, function (error) {
    // 对请求错误做些什么
    closeLoad()
    return Promise.reject(error)
})

function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toUTCString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

function clearCookie(name) {
    setCookie(name, "", -1);
}

function goLogin() {
    if (window.__POWERED_BY_QIANKUN__) { // 乾坤
        window.$goLogin()
        return
    }
    let _url = location.href
    // 加密
    // if (cfg.isEncrypt !== false) {
    //     _url += '?encrypt=1'
    // }
    _url = encodeURIComponent(_url)
    // cookies.remove('token')
    // cookies.remove('THPMSCookie')
    localStorage.removeItem('token')
    localStorage.removeItem('THPMSCookie')
    let object = '' //data.object // 暂时不启动出参
    if (!object) {
        object = location.origin + '/sso/page/login'
    }
    location.href = object + '?returnURL=' + _url
}
request.interceptors.response.use(function (response) {
    // 对响应数据做点什么
    NProgress.done()
    closeLoad()
    const data = response.data
    if (data.statusCode === 21000) {
        goLogin()
    }
    //假如是返回文件流 文件名存在header头 就返回全部的 其他就返回res.data
    if (response.request.responseType == "blob") {
        return response
    } else {
        return data
    }
}, function (error) {
    // 对请求错误做些什么
    NProgress.done()
    closeLoad()
    if (typeof error.response === 'object') {
        return Promise.reject(error.response.data)
    } else {
        return error
    }
})

export default request